<!--
 * @Author: Zhang Yingying
 * @Date: 2020-11-16 21:13:13
 * @LastEditors: Zhang Yingying
 * @LastEditTime: 2020-11-25 21:44:39
-->
<script>
  import Component from 'vue-class-component'
  import BaseDialog from '@/components/BaseDialog/index.vue'
  import classificationApi from '@/api/ClassificationApi'

  @Component({
    name: 'ClassifyDialog',
  })
  export default class ClassifyDialog extends BaseDialog {
    attrs = {
      width: '400px',
    }

    get title() {
      return '分类编辑'
    }

    get form() {
      return this.$refs.form
    }

    model = {
      parentCode: '',
      name: '',
      code: '',
    }

    props = {
      parentCode: {
        label: '上级分类',
        placeholder: '请选择上级分类',
        tag: 'el-select',
        style: {
          width: '100%',
        },
        getDataList: this.getPrimaryClassification,
        // options: [],
      },
      name: {
        label: '分类名称',
        placeholder: '请输入分类名称',
      },
      code: {
        label: '分类值',
        placeholder: '请输入分类值',
      },
    }

    config = {
      labelPosition: 'top',
    }

    opened() {
      this.getPrimaryClassification()
    }

    async getPrimaryClassification() {
      let result = []
      let resp = await classificationApi.getPrimary()
      if (resp && resp.data) {
        result = resp.data.map((x) => {
          return {
            value: x.code,
            label: x.name,
          }
        })
      }
      return result
    }

    renderBody(h) {
      return (
        <BaseForm
          ref="form"
          v-model={this.model}
          {...{
            props: {
              props: this.props,
              config: this.config,
            },
          }}
        ></BaseForm>
      )
    }

    async onSubmit() {
      try {
        let model = this.model
        this.showLoading()
        let resp = await classificationApi.save({
          ...model,
          parentCode: model.parentCode || -1,
        })
        this.closeLoading()
        if (resp && resp.code == 0) {
          this.$message.success('新增分类成功!')
          this.$emit('change')
          this.form && this.form.clearForm()
          this.onClose()
        } else {
          this.$message.error('新增分类失败!')
        }
      } catch (exp) {
        this.closeLoading()
      }
    }
  }
</script>

<style lang="scss" scoped></style>
